package com.zzzy.doc.controller.mydoc;

import com.zhuozhengsoft.pageoffice.DocumentOpenType;
import com.zhuozhengsoft.pageoffice.FileMakerCtrl;
import com.zhuozhengsoft.pageoffice.word.DataTagWriter;
import com.zhuozhengsoft.pageoffice.word.WordDocumentWriter;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.common.vo.PageResult;
import com.zzzy.doc.dao.entity.DocFileTemplate;
import com.zzzy.doc.dto.DataTagDto;
import com.zzzy.doc.service.DocFileTemplateService;
import com.zzzy.doc.service.mydoc.MyDocDraftService;
import com.zzzy.doc.vo.document.DocBasicInfoRes;
import com.zzzy.doc.vo.document.my.DocAddReq;
import com.zzzy.doc.vo.template.DocTemplateForSelectPageReq;
import com.zzzy.framework.common.annotation.RepeatSubmit;
import com.zzzy.framework.common.util.ReflectionUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Objects;

/**
 * 我的公文
 *
 * @author fc
 * @since 2024-05-27
 */
@Tag(name = "我的公文-拟稿", description = "doc108")
@Validated
@RestController
@RequestMapping("/doc/my")
public class MyDocDraftController {

    @Resource
    private MyDocDraftService myDocDraftService;
    @Resource
    private DocFileTemplateService docFileTemplateService;

    @RepeatSubmit
    @PostMapping("/add")
    @Operation(summary = "新增公文")
    @PreAuthorize("@pvs.hasPermission('doc:my:add')")
    public AjaxResult<Long> add(@Valid @RequestBody DocAddReq addReq) {
        return AjaxResult.success(myDocDraftService.addDoc(addReq));
    }

    @PostMapping("/mainAutoFill/{id}")
    @Operation(summary = "正文自动填充")
    @Parameter(name = "id", description = "公文ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:my:update')")
    public void mainAutoFill(@NotNull(message = "公文ID不能为空") @PathVariable("id") Long id
            , HttpServletRequest request, HttpServletResponse response) throws IOException {
        DocBasicInfoRes docBasicInfo = myDocDraftService.getDocBasicInfo(id);

        String openFileUrl = "/doc/my/getMainDocFileStream/" + id;
        FileMakerCtrl fmCtrl = new FileMakerCtrl(request);
        //数据标签自动填充
        WordDocumentWriter doc = new WordDocumentWriter();
        for (DataTagDto tagDto : docBasicInfo.getMainInitDataTags()) {
            DataTagWriter dataTag = doc.openDataTag(tagDto.getTagName());
            Object fieldValue = ReflectionUtil.getFieldValue(docBasicInfo, tagDto.getField());
            String value = Objects.isNull(fieldValue) ? "" : String.valueOf(fieldValue);
            dataTag.setValue(value);
        }
        fmCtrl.setWriter(doc);
        fmCtrl.fillDocumentAs(openFileUrl, DocumentOpenType.Word, docBasicInfo.getSubject());
        response.getOutputStream().print(fmCtrl.getHtml());
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除公文")
    @Parameter(name = "id", description = "公文ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:my:delete')")
    public AjaxResult delete(@NotNull(message = "公文ID不能为空") @PathVariable("id") Long id) {
        myDocDraftService.deleteById(id);
        return AjaxResult.success();
    }

    @PutMapping("/draftComplete/{id}")
    @Operation(summary = "拟稿完毕进入审核修订")
    @Parameter(name = "id", description = "公文ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:my:update')")
    public AjaxResult draftComplete(@NotNull(message = "公文ID不能为空") @PathVariable("id") Long id) {
        myDocDraftService.draftComplete(id);
        return AjaxResult.success();
    }

    @GetMapping(value = "/fileTemplate/page")
    @Operation(summary = "选择公文模板分页列表")
    @PreAuthorize("@pvs.hasPermission('doc:my:page')")
    public AjaxResult<PageResult<DocFileTemplate>> page(@Valid @ParameterObject DocTemplateForSelectPageReq queryReq) {
        PageResult<DocFileTemplate> docFileTemplatePage = docFileTemplateService.getDocFileTemplatePageForSelect(queryReq);
        return AjaxResult.success(docFileTemplatePage);
    }
}
